<?php

namespace App\Http\Controllers\Api\Merchant;

use App\ActivityRefund;
use App\DistributionOrder;
use App\Exports\OrdersExport;
use App\FictitiouShopCart;
use App\Http\Controllers\Api\PaymentController;
use App\Http\Services\CommonManager;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Images;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantStaff;
use App\OrderAddress;
use App\OrderItem;
use App\OrderRefund;
use App\Orders;
use App\PrescriptionInfo;
use App\PrescriptionInfoImgs;
use App\User;
use App\UserCoupon;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
use Maatwebsite\Excel\Facades\Excel;
use phpDocumentor\Reflection\Types\Self_;
use Log;


class OrderController extends Controller
{
    /**
     * 获取订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page           = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $keyword        = $request->get('keyword') ?? '';
        $merchantId     = $request->get('merchant_id') ?? 0;
        $deliveryMethod = $request->get('delivery_method') ?? '';
        $status         = $request->get('status') ?? '';
        $startTime      = $request->get('start_time') ?? '';
        $endTime        = $request->get('end_time') ?? '';
        $prescription   = $request->get('prescription') ?? '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        if($MerchantUser->role == 3){
            $merchantStaff = MerchantStaff::whereUserId($MerchantUser->id)->first();
            if($merchantStaff){
                $merchantId = $merchantStaff->merchant_id;
            }
        }



        /** @var Orders $order */
        $orderList = Orders::whereNull('deleted_at');

        if($keyword != ''){
            $orderAddressIds = OrderAddress::where('consignee','like','%'.trim($keyword).'%')->orWhere('phone','like','%'.trim($keyword).'%')->pluck('id');

            $orderIds = Orders::whereIn('order_address_id',$orderAddressIds)->pluck('id')->toArray();

            $MerchantMedicineIds = MerchantMedicine::where('name','like','%'.trim($keyword).'%')->pluck('id');

            $orderItemIds = OrderItem::whereIn('merchant_medicine_id',$MerchantMedicineIds)->pluck('order_id')->toArray();

            $orderIdArr = array_merge($orderIds,$orderItemIds);

            $orderList = $orderList->whereIn('id',$orderIdArr)->orWhere('order_num','like','%'.trim($keyword).'%');
        }

        if($merchantId != 0){
            $orderList = $orderList->whereMerchantId($merchantId);
        }

        if($deliveryMethod != ''){
            $orderList = $orderList->whereDeliveryMethod($deliveryMethod);
        }

        if($prescription == 1){
            $orderList = $orderList->where('prescription_info_id','>',0);
        }

        if($status !== ''){
            if ($status == 9)
                $orderList = $orderList->whereIn('status',[5,7,8]);
            else
                $orderList = $orderList->whereStatus($status);
        }

        if($startTime != '' && $endTime == ''){
            $orderList = $orderList->where('created_at','>=',$startTime);
        }

        if($startTime != '' && $endTime != ''){
            $orderList = $orderList->whereBetween('created_at',[$startTime,$endTime]);
        }

        if($startTime == '' && $endTime != ''){
            $orderList = $orderList->where('created_at','<=',$endTime);
        }

        $orderList = $orderList->whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);

        $pageInfo['total'] = $orderList->count();

        $orderList = $orderList->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($orderList) > 0){
            foreach ($orderList as $order) {
                $order->user_info = CommonManager::getUserBasicInfo($order->user_id);

                $order->merchant_name = Merchant::getMerchantName($order->merchant_id);

                $order->address_info = OrderAddress::getAddressInfo($order->order_address_id);

                $order->delivery_method_name = Merchant::getDeliveryName($order->delivery_method);

                $order->status_name = \App\Http\Controllers\Api\OrderController::getStatusName($order->status);

                $order->refund_amount = OrderRefund::getOrderRefundAmount($order->id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $orderList,'page_info' => $pageInfo]);
    }

    /**
     * 订单详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderDetail(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderId = $request->get('order_id') ?? 0;

        /** @var Orders $order */
        $order = Orders::whereId($orderId)->first();
        if($order){
            $order->user_info = CommonManager::getUserBasicInfo($order->user_id);

            $order->merchant_name = Merchant::getMerchantName($order->merchant_id);

            $order->address_info = OrderAddress::getAddressInfo($order->order_address_id);

            $order->delivery_method_name = Merchant::getDeliveryName($order->delivery_method);

            $order->status_name = \App\Http\Controllers\Api\OrderController::getStatusName($order->status);

            $order->refund_amount = OrderRefund::getOrderRefundAmount($order->id);

            $order->refund_info = OrderRefund::getOrderRefundInfo($order->id);

            $orderItemList = OrderItem::whereOrderId($order->id)->orderByDesc('created_at')->get();
            if(count($orderItemList) > 0){
                foreach ($orderItemList as $orderItem) {
                    $orderItem->goods_info = MerchantMedicine::getMedicineDetailInfo($orderItem->merchant_medicine_id);

                    $orderItem->sku_info = '';

                    $orderItem->discount_amount = $orderItem->original_price - $orderItem->discount_price;
                }
            }

            $order->order_item_list = $orderItemList;
            $order->coupon_name = UserCoupon::getUserCouponName($order->coupon_id);
            $order->prescription_info = PrescriptionInfo::getPrescriptionInfo($order->prescription_info_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $order]);
    }

    /**
     * 编辑处方信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function setOrderPrescriptionInfo(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $prescriptionInfoId = $request->input('prescription_info_id') ?? 0;
        $prescriptionImgs   = $request->input('prescription_imgs');

        $prescriptionInfo = PrescriptionInfo::whereId($prescriptionInfoId)->first();
        if(!$prescriptionInfo)
            return response()->json(['level' => 'error','message' => '处方信息不存在']);

        if($prescriptionInfo->perscriptionStatus != 99)
            return response()->json(['level' => 'error','message' => '状态异常，无法处理']);

        if(is_array($prescriptionImgs) && count($prescriptionImgs) > 0){
                $PrescriptionImgIds= PrescriptionInfoImgs::wherePrescriptionInfoId($prescriptionInfo->id)->pluck('img_id')->toArray();

                //添加
                $insertPrescriptionImgIds = array_diff($prescriptionImgs,$PrescriptionImgIds);

                //删除
                $deletePrescriptionImgIds = array_diff($PrescriptionImgIds,$prescriptionImgs);

                if(count($deletePrescriptionImgIds) > 0){
                    PrescriptionInfoImgs::wherePrescriptionInfoId($prescriptionInfo->id)->whereIn('img_id',$deletePrescriptionImgIds)->delete();
                }

                if(count($insertPrescriptionImgIds) > 0){
                    foreach ($insertPrescriptionImgIds as $insertPrescriptionImgId) {
                        $newPrescriptionImg = new PrescriptionInfoImgs();
                        $newPrescriptionImg->prescription_info_id = $prescriptionInfo->id;
                        $newPrescriptionImg->img_id = $insertPrescriptionImgId;
                        $newPrescriptionImg->save();
                    }
                }
        }else{
            $prescriptionImgList = PrescriptionInfoImgs::wherePrescriptionInfoId($prescriptionInfo->id)->get();
            if(count($prescriptionImgList) > 0){
                foreach ($prescriptionImgList as $prescriptionImg) {
                    $prescriptionImg->delete();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 设置订单发货信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setOrderShipInfo(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderId    = $request->get('order_id') ?? 0;
        $express    = $request->get('express') ?? '';
        $expressNum = $request->get('express_num') ?? '';
        $isShop     = $request->get('is_shop') ?? 0;

        if($express == '')
            return response()->json(['level' => 'error','message' => '请填写快递公司']);

        if($expressNum == '')
            return response()->json(['level' => 'error','message' => '请填写配送单号']);

        $order = Orders::whereId($orderId)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

//        if($order->status != 2)
        if(in_array($order->status,[1,4,5,6,7,9]))
            return response()->json(['level' => 'error','message' => '订单状态错误']);

//        DB::beginTransaction();
//        try {
            $order->express      = $express;
            $order->express_num  = $expressNum;
            if($isShop == 1){
//                $orderRefund =OrderRefund::whereOrderId($order->id)->whereStatus(0)->first();
//                if($orderRefund){
//                    $orderRefund->status = 2;
//                    $orderRefund->save();
//                }

                $order->express_time = date('Y-m-d H:i:s');
                $order->status   = 3;
            }
            $order->save();

//            DB::commit();
//        } catch (\Exception $e){
//            DB::rollBack();
//            return response()->json(['level' => 'error','message' => '操作失败']);
//        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $order]);
    }

    /**
     * 取消订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelOrder(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderId    = $request->get('order_id') ?? 0;

        $order = Orders::whereId($orderId)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($order->status > 1){
            return response()->json(['level' => 'error','message' => '订单已支付，暂不支持取消']);
        }

        $order->status = 6;
        $order->save();

        /** @var OrderItem $orderItem */
        $orderItemList= OrderItem::getOrderItem($order->id);
        if(count($orderItemList) > 0){
            foreach ($orderItemList as $orderItem) {
                $thisMedicine=MerchantMedicine::whereId($orderItem->merchant_medicine_id)->first();
                if($thisMedicine){
                    $thisMedicine->stock += $orderItem->num;
                    $thisMedicine->save();
                }
            }
        }

        //取消订单后改变分销订单状态
        DistributionOrder::setDistributionOrderFail($order->id);

        return response()->json(['level' => 'success','message' => '取消成功','data' => $order]);
    }

    public function confirmReceive(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $order_id   =$request->input('order_id');
        $thisOrder  =orders::whereId($order_id)->first();
        if ($thisOrder->status!=3){
            return response()->json(['level'=>'error','message'=>'当前状态不能收货哦']);
        } else {
            $thisOrder->status= 4;
            $thisOrder->receive_time= date('Y-m-d H:i:s');
            $thisOrder->save();

            \Log::error("start_order_success=================================");
            //确认订单后改变分销订单状态
            DistributionOrder::setDistributionOrderSuccess($thisOrder->id);
            \Log::error("end_order_success=================================");

            return response()->json(['level'=>'success','message'=>'已确认收货']);
        }
    }

    /**
     * 订单导出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderExport(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $keyword        = $request->get('keyword') ?? '';
        $merchantId     = $request->get('merchant_id') ?? 0;
        $deliveryMethod = $request->get('delivery_method') ?? '';
        $status         = $request->get('status') ?? '';
        $startTime      = $request->get('start_time') ?? '';
        $endTime        = $request->get('end_time') ?? '';

        if($MerchantUser->role == 3){
            $merchantStaff = MerchantStaff::whereUserId($MerchantUser->id)->first();
            if($merchantStaff){
                $merchantId = $merchantStaff->merchant_id;
            }
        }

        $fileName ='订单导出-'.$startTime.'至'.$endTime.'--'.rand(1000,9999).'.xlsx';

        /** @var Orders $order */
        $orderList = Orders::whereNull('deleted_at');

        if($keyword != ''){
            $orderAddressIds = OrderAddress::where('consignee','like','%'.trim($keyword).'%')->orWhere('phone','like','%'.trim($keyword).'%')->pluck('id');

            $orderIds = Orders::whereIn('order_address_id',$orderAddressIds)->pluck('id')->toArray();

            $MerchantMedicineIds = MerchantMedicine::where('name','like','%'.trim($keyword).'%')->pluck('id');

            $orderItemIds = OrderItem::whereIn('merchant_medicine_id',$MerchantMedicineIds)->pluck('order_id')->toArray();

            $orderIdArr = array_merge($orderIds,$orderItemIds);

            $orderList = $orderList->whereIn('id',$orderIdArr)->orWhere('order_num','like','%'.trim($keyword).'%');
        }

        if($merchantId != 0){
            $orderList = $orderList->whereMerchantId($merchantId);
        }

        if($deliveryMethod != ''){
            $orderList = $orderList->whereDeliveryMethod($deliveryMethod);
        }

        if($status !== ''){
            $orderList = $orderList->whereStatus($status);
        }

        if($startTime != '' && $endTime == ''){
            $orderList = $orderList->where('created_at','>=',$startTime);
        }

        if($startTime != '' && $endTime != ''){
            $orderList = $orderList->whereBetween('created_at',[$startTime,$endTime]);
        }

        if($startTime == '' && $endTime != ''){
            $orderList = $orderList->where('created_at','<=',$endTime);
        }

        $orderList = $orderList->whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);

        $pageInfo['total'] = $orderList->count();

        $orderIds = $orderList->orderByDesc('created_at')->pluck('id')->toArray();

        $export = new OrdersExport($orderIds);

        return Excel::download($export, $fileName);
    }

    /**
     * 订单退款接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function orderRefund(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderId       = $request->input('order_id',0);
        $refundAmount  = $request->input('refund_amount',0);
        $reason        = $request->input('reason','');
        try{
        DB::beginTransaction();
        /** @var Orders $order */
        $order = Orders::whereId($orderId)->lockForUpdate()->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($order->is_pay == 0 )
            return response()->json(['level' => 'error','message' => '订单未支付,不用退']);

//        if (in_array($order->status,[0,1,6,7,8,9]))
//            return response()->json(['level' => 'error','message' => '订单的状态不支持退款']);

        if($order->pay_amount == 0)
            return response()->json(['level' => 'error','message' => '该订单无实付金额，不需要退款']);

        if($refundAmount == 0){
            $order->status = 8;
            $order->save();
            DB::commit();
            return response()->json(['level' => 'error','message' => '已拒绝']);
        }


        if($refundAmount > $order->pay_amount)
            return response()->json(['level' => 'error','message' => '退款金额不能大于订单金额']);

            $refundNum = ToolsManager::makeBRefundNum();
            $refundResult = PaymentController::Refund($order,$reason,$refundAmount,$refundNum);
        } catch (\Exception $exception){
            DB::rollBack();
            return response()->json(['level' => 'success','message' => '配置异常，请检查是否上传了退款用的证书，错误信息：'.$exception->getMessage()]);
        }

        if($refundResult && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){

            $newActivityGroupRefund = new OrderRefund();
            $newActivityGroupRefund->order_id       = $order->id;
            $newActivityGroupRefund->order_num      = $order->order_num;
            $newActivityGroupRefund->refund_amount  = $refundAmount;
            $newActivityGroupRefund->refund_num     = $refundNum;
            $newActivityGroupRefund->remark         = $reason ?? '无';
            $newActivityGroupRefund->save();
            if($refundAmount == $order->pay_amount){
                if($order->status == 5){
                    $order->status = 7;
                }else{
                    $order->status = 6;
                }
                $order->save();
            }

            DB::commit();
            return response()->json(['level' => 'success','message' => '已向微信支付发送退款请求，预计3分钟后反馈处理结果']);
        }else{
            DB::rollBack();
            return response()->json(['level' => 'success','message' => isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '申请退款失败']);
        }
    }

    /**
     * 获取订单退款记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderRefundRecord(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit   = $request->get('limit',10);
        $page    = $request->get('page',1);
        $orderId = $request->get('order_id',0);

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $page -= 1;

        $orderRefundList = OrderRefund::whereOrderId($orderId);

        $pageInfo['total'] = $orderRefundList->count();

        $orderRefundList = $orderRefundList->orderByDesc('created_at')->offset($limit * $page)->limit($limit)->get();
        if(count($orderRefundList) > 0){
            foreach ($orderRefundList as $orderRefund) {
                if($orderRefund->status == 1){
                    $orderRefund->status_name = '退款成功';
                }elseif($orderRefund->status == 2){
                    $orderRefund->status_name = '退款失败';
                }else{
                    $orderRefund->status_name = '退款中';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $orderRefundList,'page_info' => $pageInfo]);
    }

    /**
     * 查询退款状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function orderRefundResult(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderRefundId = $request->input('order_refund_id',0);

        $orderRefund = OrderRefund::whereId($orderRefundId)->first();
        if(!$orderRefund)
            return response()->json(['level' => 'error','message' => '退款记录不存在']);

        $order = Orders::whereId($orderRefund->order_id)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        $refundResult = PaymentController::selectRefund($order,$orderRefund->refund_num);

        if(!empty($refundResult) && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
            $returnCount = !empty($refundResult['refund_count']) ? $refundResult['refund_count'] - 1 : 0;

            if($refundResult['refund_status_' . $returnCount] == 'SUCCESS'){
                $orderRefund->status      = 1;
                $orderRefund->save();

                return response()->json(['level' => 'success','message' => '退款成功']);
            }elseif($refundResult['refund_status_' . $returnCount] == 'REFUNDCLOSE'){
                $orderRefund->status      = 2;
                $orderRefund->fail_cause  = '退款关闭';
                $orderRefund->save();

                return response()->json(['level' => 'error','message' => '退款关闭']);
            }elseif($refundResult['refund_status_' . $returnCount] == 'CHANGE'){
                $orderRefund->status      = 2;
                $orderRefund->fail_cause  = '退款异常,可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。';
                $orderRefund->save();

                return response()->json(['level' => 'error','message' => '退款异常,可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。']);
            }elseif($refundResult['refund_status_' . $returnCount] == 'PROCESSING'){
                return response()->json(['level' => 'success','message' => '退款处理中']);
            }else{
                $orderRefund->status      = 2;
                $orderRefund->fail_cause  = '退款状态异常';
                $orderRefund->save();

                return response()->json(['level' => 'error','message' => '退款状态异常']);
            }
        }else{
            $orderRefund->status      = 2;
            $orderRefund->fail_cause  = isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '微信退款申请接收失败';
            $orderRefund->save();

            return response()->json(['level' => 'error','message' => isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '微信退款申请接收失败']);
        }
    }

    /**
     * 退款结果查询（加入定时任务）
     * @param Request $request
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function lookOverRefundResult(Request $request){
        /** @var OrderRefund $orderRefund */
        $orderRefundList = OrderRefund::whereStatus(0)->orderBy('created_at','desc')->get();
        if(count($orderRefundList) > 0){
            foreach($orderRefundList as $orderRefund){
                $thisOrder = Orders::whereOrderNum($orderRefund->order_num)->first();
                if($thisOrder){
                    $refundResult = PaymentController::selectRefund($thisOrder,$orderRefund->refund_num);
                    if(!empty($refundResult) && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
                        $returnCount = !empty($refundResult['refund_count']) ? $refundResult['refund_count'] - 1 : 0;

                        if($refundResult['refund_status_' . $returnCount] == 'SUCCESS'){
                            $orderRefund->status      = 1;
                            $orderRefund->save();
                        }elseif($refundResult['refund_status_' . $returnCount] == 'REFUNDCLOSE'){
                            $orderRefund->status      = 2;
                            $orderRefund->fail_cause  = '退款关闭';
                            $orderRefund->save();
                        }elseif($refundResult['refund_status_' . $returnCount] == 'CHANGE'){
                            $orderRefund->status      = 2;
                            $orderRefund->fail_cause  = '退款异常,可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。';
                            $orderRefund->save();
                        }elseif($refundResult['refund_status_' . $returnCount] == 'PROCESSING'){

                        }else{
                            $orderRefund->status      = 2;
                            $orderRefund->fail_cause  = '退款状态异常';
                            $orderRefund->save();
                        }
                    }else{
                        $orderRefund->status         = 2;
                        $orderRefund->fail_cause = isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '微信退款申请接收失败';
                        $orderRefund->save();
                    }
                }
            }
        }

        return 'success';
    }

    public function pharmacistRecommendMedicineList(Request $request){
        /** @var User $MerchantUser */
        $MerchantUser = MerchantManager::isLogin($request);
        if(!$MerchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($MerchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $limit          = $request->input('limit',20);
        $page           = $request->input('page',1);
        $keyword        = $request->get('keyword') ?? '';
        $merchantId     = $request->get('merchant_id') ?? 0;
        $startTime      = $request->get('start_time') ?? '';
        $endTime        = $request->get('end_time') ?? '';
        $status         = $request->get('status') ?? '';
        $deliveryMethod = $request->get('delivery_method') ?? '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page
        ];

        $page -= 1;

        if($MerchantUser->role == 3){
            $merchantStaff = MerchantStaff::whereUserId($MerchantUser->id)->first();
            if($merchantStaff){
                $merchantId = $merchantStaff->merchant_id;
            }
        }

        /** @var Orders $order */
        $orderList = Orders::whereEnterpriseId($enterpriseInfo->id)->whereNotNull('agent_phone_number')->where('agent_phone_number' , '<>' , '');

        if($keyword != ''){
            $orderAddressIds = OrderAddress::where('consignee','like','%'.trim($keyword).'%')->orWhere('phone','like','%'.trim($keyword).'%')->pluck('id');

            $orderIds = Orders::whereIn('order_address_id',$orderAddressIds)->pluck('id')->toArray();

            $MerchantMedicineIds = MerchantMedicine::where('name','like','%'.trim($keyword).'%')->pluck('id');

            $orderItemIds = OrderItem::whereIn('merchant_medicine_id',$MerchantMedicineIds)->pluck('order_id')->toArray();

            $orderIdArr = array_merge($orderIds,$orderItemIds);

            $orderList = $orderList->whereIn('id',$orderIdArr)->orWhere('order_num','like','%'.trim($keyword).'%');
        }

        if($merchantId != 0){
            $orderList = $orderList->whereMerchantId($merchantId);
        }

        if($deliveryMethod != ''){
            $orderList = $orderList->whereDeliveryMethod($deliveryMethod);
        }

        if($status !== ''){
            if ($status == 9)
                $orderList = $orderList->whereIn('status',[5,7,8]);
            else
                $orderList = $orderList->whereStatus($status);
        }

        if($startTime != '' && $endTime == ''){
            $orderList = $orderList->where('created_at','>=',$startTime);
        }

        if($startTime != '' && $endTime != ''){
            $orderList = $orderList->whereBetween('created_at',[$startTime,$endTime]);
        }

        if($startTime == '' && $endTime != ''){
            $orderList = $orderList->where('created_at','<=',$endTime);
        }

        $orderList = $orderList->whereEnterpriseId($enterpriseInfo->id)->whereNotNull('agent_phone_number')->where('agent_phone_number' , '<>' , '');

        $pageInfo['total'] = $orderList->count();

        $orderList = $orderList->orderByDesc('created_at')->offset($limit * $page)->limit($limit)->get();
        if(count($orderList) > 0){
            foreach ($orderList as $order) {
                $order->user_info = CommonManager::getUserBasicInfo($order->user_id);

                $order->merchant_name = Merchant::getMerchantName($order->merchant_id);

                $order->address_info = OrderAddress::getAddressInfo($order->order_address_id);

                $order->delivery_method_name = Merchant::getDeliveryName($order->delivery_method);

                $order->status_name = \App\Http\Controllers\Api\OrderController::getStatusName($order->status);

                $order->refund_amount = OrderRefund::getOrderRefundAmount($order->id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $orderList,'page_info' => $pageInfo]);
    }

    /**
     * 处方状态回调
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function prescriptionCallbackStatus(Request $request){
//        $msg = $request->input('msg');
//        $data = $request->input('data');
        $allData = $request->getContent();
//        $thisData = json_decode($Data);
        $allData = str_replace(array(" ","\r\n","\t","\n","\r"),"", $allData);

        $allData = json_decode($allData,true);

        $msg = !empty($allData['msg']) ? $allData['msg'] : '';
        $data = !empty($allData['data']) ? $allData['data'] : [];

        if($msg != "success")
            return response()->json(['code' => 400,'msg' => '消息返回失败']);

        if(empty($data['inquiryId']))
            return response()->json(['code' => 401,'msg' => '消息返回异常']);

        try {
            $inquiryId = !empty($data['inquiryId']) ? $data['inquiryId'] : '';
            /** @var PrescriptionInfo $prescriptionInfo */
            $prescriptionInfo = PrescriptionInfo::where('perscriptionNumber',$inquiryId)->first();
            if(!$prescriptionInfo)
                return response()->json(['code' => 401,'msg' => '处方信息不存在']);

            $status = $data['status'] ?? '';
            $dealDesc = $data['dealDesc'] ?? '';
            $orderFileUrl = $data['orderFileUrl'] ?? '';

            if(!empty($status))
                $prescriptionInfo->perscriptionStatus = $status;
            if(!empty($dealDesc))
                $prescriptionInfo->refuse_reason = $dealDesc;
            if(!empty($orderFileUrl)){
//                $qrcodeImgInfo = Image::make($orderFileUrl)->encode('jpg');
//                $qrcodeFile = FileManager::saveFileByFileContent($qrcodeImgInfo->encoded, 'prescription_img.jpg', $qrcodeImgInfo->mime(),"oss");
//                $imageModel = Images::whereFileId($qrcodeFile->id)->first();
//                if(!$imageModel){
//                    $imageModel = new Images();
//                    $imageModel->files()->associate($qrcodeFile);
//                    $imageModel->img_type = $qrcodeFile->file_type;
//                    $imageModel->img_name = $qrcodeFile->file_name;
//                    $imageModel->save();
//                }

                $prescriptionInfoImg = PrescriptionInfoImgs::wherePrescriptionInfoId($prescriptionInfo->id)->whereImgUrl($orderFileUrl)->first();
                if(!$prescriptionInfoImg){
                    $prescriptionInfoImg = new PrescriptionInfoImgs();
                    $prescriptionInfoImg->prescription_info_id = $prescriptionInfo->id;
//                    $prescriptionInfoImg->img_id               = $imageModel->id;
                    $prescriptionInfoImg->img_url              = $orderFileUrl;
                    $prescriptionInfoImg->save();
                }
            }

            $prescriptionInfo->save();
        } catch (\Exception $e) {
            Log::error('prescriptionCallbackStatus：message=>' . $e->getMessage());
            return response()->json(['code' => 402,'msg' => '回调失败']);
        }

        return response()->json(['code' => 200,'msg' => 'success','data' => $prescriptionInfo]);
    }

}
